package six_dirct_Exchange;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import util.RabbitMqUtils;

/**
 * @BelongsProject: RabbitMQ
 * @BelongsPackage: workQueue
 * @Author: HUI
 * @CreateTime: 2022-04-13 09:48
 * @Description: 接收消息
 */
public class MyWorks {

    private static final String EXCHANGE_NAME = "direct_logs";

    public void getWork() throws Exception {
        String threadName = Thread.currentThread().getName();
        Channel channel = RabbitMqUtils.getChannel();

        //指定交换机模式
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);

        /**
         * 生成一个临时的队列队列的名称是随机的
         * 当消费者断开和该队列的连接时队列自动删除
         */
        String queueName = channel.queueDeclare().getQueue();
        System.out.println("队列名字：" + queueName);

        //将临时队列与交换机进行绑定，routingKey是队列与交换机的之间的绑定key
        if ("main".equalsIgnoreCase(threadName)) {
            channel.queueBind(queueName, EXCHANGE_NAME, "error");
        } else {
            channel.queueBind(queueName, EXCHANGE_NAME, "info");
            channel.queueBind(queueName, EXCHANGE_NAME, "warning");
        }

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String receivedMessage = new String(delivery.getBody());
            System.out.println(threadName + "接收到消息:" + receivedMessage);
        };

        CancelCallback cancelCallback = (consumerTag) -> {
            System.out.println(consumerTag + "消费者取消消费接口回调逻辑");
        };

        System.out.println(threadName + "消费者启动等待消费.................. ");
        channel.basicConsume(queueName, true, deliverCallback, cancelCallback);
    }


    public static void main(String[] args) throws Exception {
        new Thread(() -> {
            try {
                new MyWorks().getWork();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();


        new MyWorks().getWork();

    }
}



